package io.renren.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zaxxer.hikari.HikariDataSource;
import io.renren.service.SysGeneratorService;
import io.renren.utils.PageUtils;
import io.renren.utils.Query;
import io.renren.utils.R;
import org.apache.commons.io.IOUtils;
import org.dc.jdbc.core.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年12月19日 下午9:12:58
 */
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController {
	@Autowired
	private SysGeneratorService sysGeneratorService;
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params) throws Exception{
		//查询列表数据
		Query query = new Query(params);
		List<Map<String, Object>> list = sysGeneratorService.queryList(query);
		int total = sysGeneratorService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());


		HikariDataSource dataSource1 = new HikariDataSource();
		dataSource1.setJdbcUrl("jdbc:mysql://localhost:3306/idcenter?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false");
		dataSource1.setUsername("root");
		dataSource1.setPassword("root");
		dataSource1.setConnectionTimeout(1000);

		DBHelper testDbHelper = new DBHelper(Lists.newArrayList(dataSource1));

		String sql = "select table_name tableName, engine, table_comment tableComment, create_time createTime from information_schema.tables " +
				" where table_schema = (select database()) ";
		List<Map<String, Object>> listMap = testDbHelper.selectList(sql,null);
		System.out.println(listMap);


		return R.ok().put("page", pageUtil);
	}

	/**
	 * 生成代码
	 */
	@RequestMapping("/code")
	public void code(String tables, HttpServletResponse response) throws IOException{
		byte[] data = sysGeneratorService.generatorCode(tables.split(","));

		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"renren.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}

	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/dbinfolist")
	public R dbinfolist(Map<String, Object> params){
		List<Map<String, Object>> dblist = sysGeneratorService.queryDbInfoList();

		return R.ok().put("dblist",dblist);
	}
}
